﻿using Models.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using yymbBLL;

namespace WebApp_WB.Controllers
{
    [ValidateInput(false)]
    public class My_HomeController : Controller
    {
        private OtherManger db = new OtherManger();
        private My_homeManger mm = new My_homeManger();
        private PsdataManger _db = new PsdataManger();
        private yymbDBEntities _efdb = new yymbDBEntities();
        private LikeManger lk = new LikeManger();
        // GET: Other
        public ActionResult My_Home(int id)
        {
            ViewBag.like = lk.Like(id);
            ViewBag.popu = lk.popu(id);
            ViewBag.Information = _efdb.Information.Find(id);//基本信息
            ViewBag.User = _efdb.User.Find(id);//注册信息
            ViewBag.Education = _efdb.Education.Where(e=>e.UserID==id).FirstOrDefault();//学历信息
            ViewBag.Occupation = _efdb.Occupation.Where(o=>o.UserID == id).FirstOrDefault();//职业信息
            ViewBag.Personality = _efdb.Personality_tag.Where(p => p.UserID == id);//个性标签

            ViewBag.guan = _efdb.User_rs.Include("Information1").Where(u=>u.UserID==id);//自己关注的人

            ViewBag.Follow = db.GetUserFollow(id);
            ViewBag.atte = db.Oth_use_atte(id);
            ViewBag.fans = db.Oth_use_fans(id);
            ViewBag.SumWB = db.SumWB(id);
            return View(db.Oth_use_Info(id));
        }
        /// <summary>
        /// 发微博
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        /// 
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Microblog(string txt, string url, List<HttpPostedFileBase> file)
        {
            int uid = (int)Session["UserID"];
            ViewBag.uid = (int)Session["UserID"];
            string mp = Server.MapPath("~/images/");
            List<WB_pic> wp = new List<WB_pic>();
            if (this.CreateFolderIfNeeded(mp))
            {
                if (file[0] != null)
                {
                    foreach (var item in file)
                    {                       
                        WB_pic wb = new WB_pic();
                        wb.URL = item.FileName;
                        wp.Add(wb);
                        item.SaveAs(mp + item.FileName);
                    }
                }
            }
            if (mm.Microblog(uid, txt, url, wp))
            {
                return RedirectToAction("My_Home/" + uid);
            }
            return View();
        }
        /// <summary>
        /// 用户微博搜索
        /// </summary>
        /// <param name="id"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetMicroblog(int size, int index, int uid,string str)
        {
            _efdb.Configuration.ProxyCreationEnabled = false;
            var data = _efdb.Microblog.Include("WB_pic").Include("Information").Include("Comment").Where(n => n.UserID == uid&&n.Content.Contains(str)).OrderByDescending(n => n.Release_time).
                    Select(n => new {
                        MbID = n.MbID,
                        Type = n.Type,
                        Content = n.Content,
                        Url = n.Url,
                        Release_time = n.Release_time.ToString(),
                        Forward = _efdb.Microblog.Where(m => m.FwID == n.MbID).ToList().Count(),
                        Likes = n.Likes.Count(),
                        UserID = n.UserID,
                        Photo = n.Information.Photo,
                        Nickname = n.Information.Nickname,
                        WB_pic = n.WB_pic,
                        Comment = n.Comment.ToList(),
                        Fw = _efdb.Microblog.Where(m => m.MbID == n.FwID).Select(m => new {
                            MbID = m.MbID,
                            Type = m.Type,
                            Content = m.Content,
                            Url = m.Url,
                            Release_time = m.Release_time.ToString(),
                            UserID = m.UserID,
                            Photo = m.Information.Photo,
                            Nickname = m.Information.Nickname,
                            WB_pic = m.WB_pic,
                        }).ToList()
                    }).
                    Skip(size * (index - 1)).Take(size).ToList();
            return Json(data);

        }

        /// <summary>
        /// 用户微博搜索（高级搜索）
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="type"></param>
        /// <param name="str"></param>
        /// <param name="before"></param>
        /// <param name="now"></param>
        /// <returns></returns>
        public JsonResult GetMicroblogs(int size, int index, int uid, int[] type, string str, DateTime before, DateTime now)
        {
            _efdb.Configuration.ProxyCreationEnabled = false;
            var data = _efdb.Microblog.Include("WB_pic").Include("Information").Include("Comment").Where(n => n.UserID == uid && n.Content.Contains(str)).OrderByDescending(n => n.Release_time).
                    Select(n => new {
                        MbID = n.MbID,
                        Type = n.Type,
                        Content = n.Content,
                        Url = n.Url,
                        Release_time = n.Release_time.ToString(),
                        Forward = _efdb.Microblog.Where(m => m.FwID == n.MbID).ToList().Count(),
                        Likes = n.Likes.Count(),
                        UserID = n.UserID,
                        Photo = n.Information.Photo,
                        Nickname = n.Information.Nickname,
                        WB_pic = n.WB_pic,
                        Comment = n.Comment.ToList(),
                        Fw = _efdb.Microblog.Where(m => m.MbID == n.FwID).Select(m => new {
                            MbID = m.MbID,
                            Type = m.Type,
                            Content = m.Content,
                            Url = m.Url,
                            Release_time = m.Release_time.ToString(),
                            UserID = m.UserID,
                            Photo = m.Information.Photo,
                            Nickname = m.Information.Nickname,
                            WB_pic = m.WB_pic,
                        }).ToList()
                    }).
                    Skip(size * (index - 1)).Take(size).ToList();
            //是否包含原创微博
            if (type[0] != 1)
            {
                data.RemoveAll(p => p.Type == "原创");
            }
            //是否包含转发微博
            if (type[1] != 1)
            {
                data.RemoveAll(p => p.Type == "转发");
            }
            //是否是纯文字微博
            if (type[2] != 1)
            {
                data.RemoveAll(p =>p.Content.Contains(".jpg"));
            }
            //是否是含图片的微博
            if (type[3] != 1)
            {
                data.RemoveAll(p =>p.WB_pic==null);
            }
            //是否含视频
            if (type[4] != 1)
            {
                data.RemoveAll(p => p.Url.Contains(".mp4"));
            }
            //是否含音乐
            if (type[5] != 1)
            {
                data.RemoveAll(p => p.Url.Contains(".mp3"));
            }
            return Json(data);
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="size"></param>
        /// <param name="index"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetMBlogpage(int size, int index, int id)
        {
            _efdb.Configuration.ProxyCreationEnabled = false;
            var data = _efdb.Microblog.Include("WB_pic").Include("Information").Include("Comment").Where(n => n.UserID == id).OrderByDescending(n => n.Release_time).
                    Select(n => new {
                        MbID = n.MbID,
                        Type = n.Type,
                        Content = n.Content,
                        Url = n.Url,
                        Release_time = n.Release_time.ToString(),
                        Forward = _efdb.Microblog.Where(m => m.FwID == n.MbID).ToList().Count(),
                        Likes = n.Likes.Count(),
                        UserID = n.UserID,
                        Photo = n.Information.Photo,
                        Nickname = n.Information.Nickname,
                        WB_pic = n.WB_pic,
                        Comment = n.Comment.ToList(),
                        Fw = _efdb.Microblog.Where(m => m.MbID == n.FwID).Select(m => new {
                            MbID = m.MbID,
                            Type = m.Type,
                            Content = m.Content,
                            Url = m.Url,
                            Release_time = m.Release_time.ToString(),
                            UserID = m.UserID,
                            Photo = m.Information.Photo,
                            Nickname = m.Information.Nickname,
                            WB_pic = m.WB_pic,
                        }).ToList()
                    }).
                    Skip(size * (index - 1)).Take(size).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Info(HttpPostedFileBase file, Information information)//保存基本信息
        {
            if (file!=null)
            {
                file.SaveAs(Server.MapPath("/picture/" + file.FileName));
                information.Photo = file.FileName;
            }
           
            //information.UserID =Convert.ToInt32(Session["UserID"].ToString());
            _db.informations(information);
            return RedirectToAction("My_Home/"+information.UserID);
        }
        public ActionResult images()
        {
            return View();
        }
    
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    //TODO：处理异常
                    result = false;
                }
            }
            return result;
        }
    public JsonResult Education(Education education)//保存学历信息
        {
            _db.educations(education);
            return Json(education,JsonRequestBehavior.AllowGet);
        }
        public JsonResult Use(User user)//保存注册信息
        {
            _db.users(user);
            return Json(user, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Occ(Occupation occupation)//保存职业信息
        {
            _db.occupations(occupation);
            return Json(occupation, JsonRequestBehavior.AllowGet);
        }

        public void Pers(int id)//删除标签
        {
            _efdb.Personality_tag.Remove(_efdb.Personality_tag.Find(id));            
        }

        public void Delwb(int mbid)
        {
          var wb=_efdb.Microblog.Find(mbid);
            _efdb.Microblog.Remove(wb);
            _efdb.SaveChanges();
        }
        public JsonResult qui(int? uid, int? pid)
        {
            _efdb.Configuration.ProxyCreationEnabled = false;
            var n=_efdb.User_rs.Where(u => u.UserID == uid && u.Use_UserID == pid).SingleOrDefault();
            _efdb.User_rs.Remove(n);
            if (_efdb.SaveChanges()>0)
            {
                var data = _efdb.User_rs.Include("Information1").Where(u => u.UserID == (int)uid)
                    .Select(u => new
                    {
                        Nickname = u.Information1.Nickname,
                        E_mail = u.Information1.E_mail==null?"":u.Information1.E_mail,
                        Creation_time = u.Creation_time.ToString(),
                        UserID = u.UserID,
                        Use_UserID = u.Use_UserID

                    }).ToList();
                return Json(data,JsonRequestBehavior.AllowGet);//自己关注的人
            }
            return Json(0);
        }
    }
}